//
//  TSMsgEditTableViewController.m
//  chart
//
//  Created by xu on 15/8/13.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSMsgEditTableViewController.h"
#import "TSMsgContentItemCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "TSMsgModel.h"
#import "TSReceiveMsgEditExtendStepViewController.h"
#import "TSFileTools.h"
@interface TSMsgEditTableViewController ()<UIDocumentInteractionControllerDelegate>

@end

@implementation TSMsgEditTableViewController{
    NSArray *dataArray;
    NSArray *dataEntrustArray;
    NSArray *dataVacateArray;
    
    NSArray *actionArray;
    TSMsgModel *msgEditModel;
    QSFetchModel *actionModel;
    
    UIDocumentInteractionController *docInteractionController;
}

@synthesize msgId, isAudit;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *right_btn_item = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(onRightItemClick:)];
    self.navigationItem.rightBarButtonItem = right_btn_item;
    
    actionArray = isAudit?@[@"通过", @"拒绝"]:@[@"已读",@"确定", @"委托", @"请假"];
    dataArray = @[@"标题:", @"时间:", @"地点:", @"内容:", @"操作:", @"发送人:",@"类型:", @"附件:", @"时限:"];
    actionModel = [[QSFetchModel alloc] init];
    
    msgEditModel = [[TSMsgModel alloc] init];
    WS(weakSelf);
    msgEditModel.requestParams = @{TSDictionaryKeyDefine_Id:msgId?:@""};
    [msgEditModel fetchWithPath:isAudit?kRequestUrl_AuditMessage_outList_messageinfo:kRequestUrl_SendMessage_outOne_messageinfo completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        [weakSelf.tableView reloadData];
    } NoProgress:NO];
}

- (void)onRightItemClick:(id)sender
{
    TSPickerViewTextFieldCell *picker_cell =  (TSPickerViewTextFieldCell *)[self getCellByTitle:@"操作:"];
    
    NSString *action_text = picker_cell.contentTextField.text;
    [self makeAction:action_text];
}



- (void)makeAction:(NSString *)actionText
{
    /* 接收信息和审核 */
    if ([actionText isEqualToString:[actionArray objectAtIndex:0]]) {
        if (isAudit) {
            [self sendActionToServer:kRequestUrl_AuditMessage_audit];
        }
        else{
            [self sendActionToServer:kRequestUrl_SendMessage_read];
        }
    }else if ([actionText isEqualToString:[actionArray objectAtIndex:1]]) {
        if (isAudit) {
            [self pushNextStepViewController:Action_Type_Reject];
        }
        else{
            [self sendActionToServer:kRequestUrl_SendMessage_affirm];
        }
    }
    else if ([actionText isEqualToString:[actionArray objectAtIndex:2]]){
        [self pushNextStepViewController:Action_Type_Entrust];
    }
    else if ([actionText isEqualToString:[actionArray objectAtIndex:3]]){
        
        [self pushNextStepViewController:Action_Type_Vacate];
    }
}

- (void)pushNextStepViewController:(Action_Type)type
{
    TSReceiveMsgEditExtendStepViewController *step_vc = [[TSReceiveMsgEditExtendStepViewController alloc] init];
    step_vc.msgId = msgId;
    step_vc.currentAction = type;
    
    [self.navigationController pushViewController:step_vc animated:YES];
}

- (void)sendActionToServer:(NSString *)url
{
    WS(weakSelf);
    actionModel.requestParams = @{TSDictionaryKeyDefine_Id:msgId};
    [actionModel fetchWithPath:url completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (isSucceeded) {
            if(!isAudit){
                [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessageChangeActionSucceeded object:nil];
            }else{
                
                [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessageChangeSucceeded object:nil];
            }
            [[LBToastManager manager] showtoast:@"操作成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } NoProgress:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    if([title isEqualToString:@"内容:"]){
        return 200;
    }else{
        return CELL_HEIGHT;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    if ([title isEqualToString:@"操作:"]) {
        TSPickerViewTextFieldCell *picker_cell = [tableView dequeueReusableCellWithIdentifier:@"pickerCell"];
        if (!picker_cell) {
            picker_cell = [[TSPickerViewTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pickerCell" WithSourceArray:actionArray];
        }
        [picker_cell setTitle:title];
        return picker_cell;
    }
    else if ([title isEqualToString:@"附件:"]){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
            
            UIButton *btn = [self createButton:CGRectMake(100.f, MARGIN_TOP, 100.f, CELL_HEIGHT-2*MARGIN_TOP) WithTitle:@"下载附件"];
            [btn.titleLabel setFont:FONT(12.f)];
            [cell.contentView addSubview:btn];
        }
        cell.textLabel.text = title;
        [cell.textLabel setFont:FONT(12.f)];
        
        return cell;
    }
    else{
        TSMsgContentItemCell *content_cell = [tableView dequeueReusableCellWithIdentifier:@"contentCell"];
        if (!content_cell) {
            content_cell = [[TSMsgContentItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"contentCell"];
        }
        [content_cell setTitleAndTextField:title Type:UITextFieldDefault];
        [content_cell setTextFieldEditable:NO];
        [content_cell.contentTextField setText:[self getTextByTitle:[dataArray objectAtIndex:indexPath.row]]];
        
        if([title isEqualToString:@"内容:"]){
            content_cell.contentTextField.frame=CGRectMake( content_cell.contentTextField.frame.origin.x,  content_cell.contentTextField.frame.origin.y, content_cell.contentTextField.frame.size.width, 200);
        }
        return content_cell;
    }
    
    return nil;
}


- (NSString *)getTextByTitle:(NSString *)title
{
    NSString *result_text = @"";
    dataArray = @[@"标题:", @"时间:", @"地点:", @"内容:", @"操作:", @"发送人:",@"类型:", @"附件:", @"时限:"];
    if (msgEditModel) {
        if ([title isEqualToString:@"标题:"]) {
            result_text = msgEditModel.title;
        }
        else if ([title isEqualToString:@"时间:"]){
            result_text = [TSTools getDateByTime:msgEditModel.time];
        }
        else if ([title isEqualToString:@"地点:"]){
            result_text = msgEditModel.place;
        }
        else if ([title isEqualToString:@"内容:"]){
            result_text = msgEditModel.messageData;
        }
        else if ([title isEqualToString:@"发送人:"]){
            result_text = msgEditModel.nameSend;
        }
        else if ([title isEqualToString:@"时限:"]){
            result_text = [NSString stringWithFormat:@"%@分钟", msgEditModel.timeLimit];
        }
        else if ([title isEqualToString:@"类型:"]){
            result_text = [msgEditModel.messageType isEqualToString:@"1"]?@"通知":@"文件";
        }
    }
    
    return result_text;
}

- (UIButton *)createButton:(CGRect)frame WithTitle:(NSString *)title
{
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn.layer.borderWidth = .5f;
    
    return btn;
}

- (void)onBtnClick:(UIButton *)btn
{
    if(msgEditModel.attachment.count<=0){
        [TSTools showAlert:@"无附件下载"];
    }else{
         [[LBToastManager manager] showprogress:nil];
        
        TSFileModel *fileModel = [msgEditModel.attachment objectAtIndex:0];
//        [TSFileTools downloadFileURL:[NSString stringWithFormat:@"%@:80%@", BASE_URL,@"/test/a.a"] savePath:[TSFileTools getCacheFileDir] fileName:fileModel.upload tag:0];
        [TSFileTools download:[NSString stringWithFormat:@"%@:80%@", BASE_URL,fileModel.download] name:fileModel.upload downloadHandler:^(NSString * path){
             //[TSTools showAlert:@"下载成功"];
            //[TSFileTools openMenu:self.view delete:self filePath:path];
            
            [ self setupDocumentControllerWithURL:[NSURL fileURLWithPath:path]];
            
            CGRect rect = CGRectMake ( 0 , 0 , currentDeviceWidth , 200 );
            
            //    [self.docInteractionController presentOptionsMenuFromRect:rect inView:self.view  animated:YES];//包含快速预览菜单
            
            [docInteractionController presentOpenInMenuFromRect :rect inView : self.view animated : YES ]; //不包含包含快速预览菜单
            [[LBToastManager manager] hideprogress];
        }];
    }
    
}

- ( void )setupDocumentControllerWithURL:( NSURL *)url

{
    
    if ( docInteractionController == nil ){
        
        docInteractionController=[UIDocumentInteractionController interactionControllerWithURL :url];
        
        docInteractionController.delegate = self ;
        
    }
    
    else {
        
       docInteractionController.URL = url;
        
    }
    
}

- (UITableViewCell *)getCellByTitle:(NSString *)title
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[self getIndexPathByTitle:title]];
    return cell;
}

- (NSIndexPath *)getIndexPathByTitle:(NSString *)title
{
    if (dataArray) {
        for (int i=0; i<dataArray.count; i++) {
            if ([[dataArray objectAtIndex:i] isEqualToString:title]) {
                NSIndexPath *index_path = [NSIndexPath indexPathForItem:i inSection:0];
                return index_path;
            }
        }
    }
    
    return nil;
}

- ( UIViewController *)documentInteractionControllerViewControllerForPreview:( UIDocumentInteractionController *)interactionController{
    
    return self ;
    
}

// 不显示 copy print

- ( BOOL )documentInteractionController:( UIDocumentInteractionController *)controller canPerformAction:( SEL )action{
    
    return NO ;
    
}

- ( BOOL )documentInteractionController:( UIDocumentInteractionController *)controller performAction:( SEL )action{
    
    return NO ;
    
}

@end
